package demo.error;

import demo.common.ResultJson;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
    // 返回json格式的错误信息到客户端
    @ExceptionHandler(value = StringIndexOutOfBoundsException.class)
    public ResponseEntity<ResultJson> jsonException(StringIndexOutOfBoundsException e) {
        ResultJson resultJson = ResultJson.error().message(e.toString()).data("exception", e);
        return new ResponseEntity<>(resultJson, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 用自定义的jsp页面显示异常信息
    @ExceptionHandler(value = ArithmeticException.class)
    public String errorJsp(Model model, WebRequest request, ArithmeticException e) {
        model.addAttribute("request", request);
        model.addAttribute("exception", e);
        return "error/error";
    }
}
